package net.sevear.chaos.recommend
{
	import com.adobe.serialization.json.JSON;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.utils.setTimeout;
	
	import mx.rpc.events.ResultEvent;
	
	import net.sevear.chaos.event.ChaosErrorEvent;
	
	public class ChaosRemoteRequest extends EventDispatcher
	{
		private var _tryTotal:int
		private var _trytimes:int;
		private var _resultFunc:Function;
		private var _rst:URLRequest;
		private var loader:URLLoader;
		private var isSendingRequest:Boolean;
		
		private static const SUCCESSUL_CODE:int = 0;
		public function ChaosRemoteRequest(trytimes:int)
		{
			super();
			_tryTotal = trytimes;
			isSendingRequest = false;
			loader = new URLLoader();
			loader.addEventListener(Event.COMPLETE,onComplete);
			loader.addEventListener(IOErrorEvent.IO_ERROR,onIOError);
		}
		
		public function sendRequest(rst:URLRequest,resultHandler:Function):void{
			if(isSendingRequest == false){
				_trytimes = 0;
				_resultFunc = resultHandler;
				_rst = rst;
				isSendingRequest = true;
				loader.load(rst);
			}
		}
		
		/**
		 * {errcode:int,errmsg:string,content:string}
		 * */
		private function onComplete(e:Event):void{
			isSendingRequest = false;
			var rst:String = (e.currentTarget as URLLoader).data as String;
			try{
				var obj:Object = JSON.decode(rst);
				if(obj.errcode!=0){
					var errcode:int = obj.errcode as int;
					var errmsg:String = obj.errmsg as String;
					var content:String = obj.content as String;
					var errev:ChaosErrorEvent = new ChaosErrorEvent(errcode,errmsg,content);
					dispatchEvent(errev);
				}else{
					if(_resultFunc!=null){
						_resultFunc(obj.content);
					}
				}
			}catch(e:Error){
				if(_resultFunc!=null){
					_resultFunc(obj.content);
				}
			}
			
		}
		
		private function tryFunc():void{
			isSendingRequest = true;
			loader.load(_rst);
		}
		
		private function onIOError(e:IOErrorEvent):void{
			isSendingRequest = false;
			if(_tryTotal > 0 ){
				if(_trytimes<_tryTotal){
					try{
						loader.close()
					}catch(e:Error){
						trace(e.message);
					}
					_trytimes++;
					setTimeout(tryFunc,50);
				}
			}else{
				//TODO:dispatch a ioerror event
//				dispatchEvent(new ChaosErrorEvent
			}
		}
	}
}